<?php
/**
 * 公共控制类
 * @author 大梦
 * @DateTime 2019/07/06
 */

namespace app\index\controller;

use think\Controller;
use think\Request;
use think\Db;
use EasyWeChat\Factory;
use app\common\model\Member as MemberModel;
use app\common\model\VotePeriod as VotePeriodModel;

class Common extends Controller
{
    const SUCCESS_CODE = 1;
    const ERROR_CODE = 0;
    protected $request;
    
    public function initialize()
    {

        parent::initialize();

        $wechat = [
            'app_id' => '',
            'timestamp' => '',
            'nonce_str' => '',
            'signature' => '',
        ];

        $config = [
            'app_id' => config('wechat.appid'),
            'secret' => config('wechat.secret'),
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
            'oauth' => [
                'scopes' => ['snsapi_userinfo'],
            ],
        ];

        // 使用EasyWeChat
        $app = Factory::officialAccount($config);

        $wechat = $app->jssdk->buildConfig(array('updateAppMessageShareData', 'updateTimelineShareData'), true);

        $domain = request()->domain();

        $where_period = [
            ['is_del', 'eq', 0],
            ['is_valid', 'eq', 1],
        ];
        $this->current_vote_info = (new VotePeriodModel())->where($where_period)->order('id desc')->find();

        $info = [
            'web_title' => $this->current_vote_info['title'] . ' - 实干家科技集团',
            'desc' => '做真正的实干家，而不仅仅是思考者！～',
            'link' => $domain,
            'imgUrl' => config('qiniu.base_host') . 'img_bg_award_small.jpg',
            'wechat' => json_decode($wechat, true),
        ];
        $this->assign($info);
    }

    public function api_success($msg, $data = [])
    {
        $return['msg'] = $msg;
        $return['data'] = $data;
        $return['code'] = SELF::SUCCESS_CODE;

        return json($return);
    }

    public function api_error($msg, $data = [])
    {
        $return['msg'] = $msg;
        $return['data'] = $data;
        $return['code'] = SELF::ERROR_CODE;

        return json($return);
    }

    public function api_response($msg, $data, $code)
    {
        $return['msg'] = $msg;
        $return['data'] = $data;
        $return['code'] = $code;

        return json($return);
    }
}
